package com.hj.system.system.controller;

import com.hj.system.base.annotation.SystemLog;
import com.hj.system.base.domain.Tree;
import com.hj.system.base.utils.MD5Utils;
import com.hj.system.base.utils.PageUtils;
import com.hj.system.base.utils.ResponseUtil;
import com.hj.system.base.utils.ShiroUtils;
import com.hj.system.common.controller.BaseController;
import com.hj.system.common.service.FileService;
import com.hj.system.system.domain.MenuDO;
import com.hj.system.system.service.MenuService;
import com.hj.system.system.service.UserFingerService;
import com.hj.system.system.shiro.UserNameLoginToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    UserFingerService userFingerService;

    @GetMapping({"/", ""})
    public String home() {
        return "redirect:/login";
    }

    @GetMapping("/main")
    public String welcome() {
        return "main";
    }

    @SystemLog("请求访问主页")
    @GetMapping({"/index"})
    public String index(Model model, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String client = "";
        for (Cookie cookie : cookies) {
            if ("client".equalsIgnoreCase(cookie.getName())) {
                client = cookie.getValue();
            }
        }
        if (client == null || "".equalsIgnoreCase(client)) {
            client = "index";
            List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
            model.addAttribute("menus", menus);
        } else {
            List<MenuDO> menus = menuService.listByMain(client);
            model.addAttribute("menus", menus);
        }
        model.addAttribute("user", ShiroUtils.getUser());
        return client;
    }

    @GetMapping("/login")
    public String login(String client, HttpServletResponse response,HttpServletRequest request) {
        Map<String, String[]> param = request.getParameterMap();
        param.forEach((m,n)->{
            Cookie cookie = new Cookie(m, n[0]);
            response.addCookie(cookie);
        });
        return "login";
    }

    @ResponseBody
    @GetMapping("/api/user/finger/list")
    public Map<String, Object> list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtils = userFingerService.list(params);
        return ResponseUtil.okContent(pageUtils);
    }

    @SystemLog("登录")
    @PostMapping("/login")
    @ResponseBody
    public ResponseUtil ajaxLogin(String username, String password, @RequestParam(required = false, defaultValue = "md5") String loginType) {
        UserNameLoginToken token;
        if ("md5".equals(loginType)) {
            password = MD5Utils.encrypt(username, password);
        }
        if ("finger".equals(loginType)) {
            token = UserNameLoginToken.buildNoPassword(username, loginType);
        } else {
            token = UserNameLoginToken.buildPassword(username, password, loginType);
        }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResponseUtil.ok();
        } catch (AuthenticationException e) {
            return ResponseUtil.error(e.getMessage());
        }
    }

    @GetMapping("/logout")
    public String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

}
